using MQTTnet;
using System.Text.Json;

namespace AIoTGateway_UI.Services;

public class MQTTService
{
    private IMqttClient _mqttClient;
    private MqttClientOptions _options;

    public MQTTService()
    {
        try
        {
            var factory = new MqttClientFactory(); // 修复了 MqttFactory 的命名空间问题

            _mqttClient = factory.CreateMqttClient();

            _options = new MqttClientOptionsBuilder()
                .WithTcpServer("broker.emqx.io", 1883) // MQTT broker地址    
                .WithClientId("AIoTGateway")
                .Build();

            ConnectAsync().Wait();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

    private async Task ConnectAsync()
    {
        await _mqttClient.ConnectAsync(_options);
    }

    public async Task PublishAsync(string topic, object payload)
    {
        if (!_mqttClient.IsConnected)
        {
            await ConnectAsync();
        }

        var message = new MqttApplicationMessageBuilder()
            .WithTopic(topic)
            .WithPayload(JsonSerializer.Serialize(payload))
            .Build();

        await _mqttClient.PublishAsync(message);
    }

    public void Dispose()
    {
        _mqttClient?.DisconnectAsync().Wait();
        _mqttClient?.Dispose();
    }
}
